package types

import (
	"time"

	"gorm.io/gorm"

	"torler.com/qingyue/pkg/tools"
)

// 表基础字段
type Basic struct {
	CreatedAt time.Time `gorm:"column:ctime;type:datetime(0);autoCreateTime"`
	UpdatedAt time.Time `gorm:"column:utime;type:datetime(0);autoUpdateTime"`
	//软删除字段标记
	DeletedAt gorm.DeletedAt `gorm:"column:delat;type:datetime(0)"`
}

// GORM 钩子，用于在创建记录前设置创建时间
func (basic *Basic) BeforeCreate(tx *gorm.DB) (err error) {
	now := tools.NewNowTime()
	if basic.CreatedAt.IsZero() {
		basic.CreatedAt = now
	}
	if basic.UpdatedAt.IsZero() {
		basic.UpdatedAt = now
	}

	return nil
}

// GORM 钩子，用于在更新记录前设置更新时间
func (basic *Basic) BeforeUpdate(tx *gorm.DB) (err error) {
	now := tools.NewNowTime()
	if basic.UpdatedAt.IsZero() {
		basic.UpdatedAt = now
	}
	return nil
}
func (basic *Basic) HasChanged() bool {
	return basic.UpdatedAt != basic.CreatedAt
}
